package com.twu.biblioteca;

import com.twu.biblioteca.entity.Book;
import com.twu.biblioteca.repository.BookRepository;

import java.util.*;

/**
 * Created by ccsong on 9/16/14.
 */
public class BookList implements NormalList
{

    private  static Hashtable<Book,Boolean> bookDictionary = new Hashtable<Book, Boolean>();
    private BookRepository bookRepository;
    public BookList(){
        bookDictionary.put(BookRepository.book1,true);
        bookDictionary.put(BookRepository.book2,true);
        bookDictionary.put(BookRepository.book3,true);
        bookDictionary.put(BookRepository.book4,false);

    }

    @Override
    public boolean containAndCheck(String name){
        boolean isContain = false;

        Iterator iterator = bookDictionary.keySet().iterator();
        while(iterator.hasNext()){
            Book book = (Book)iterator.next();
            if(book.isMatch(name) && bookDictionary.get(book)) {
                bookDictionary.put(book,false);
                    isContain = true;
                    break;
            }
        }
        return isContain;
    }

    @Override
    public String toString(){
        String bookList = "\n";
        Iterator iterator = bookDictionary.keySet().iterator();
        while(iterator.hasNext()){
            bookList += ((Book)iterator.next());
        }
        return bookList;
    }

    public boolean belongAndReturn(String bookName) {
        boolean isBelong = false;
        Iterator iterator = bookDictionary.keySet().iterator();
        while(iterator.hasNext()){
            Book book = (Book) iterator.next();
            if(book.isMatch(bookName) && !bookDictionary.get(book)){
                bookDictionary.put(book,true);
                isBelong = true;
                break;
            }
        }
        return isBelong;
    }

    public Book getBook(String name) {
        Book matchedBook = new Book();
        Iterator iterator = bookDictionary.keySet().iterator();
        while (iterator.hasNext()) {
            Book book = (Book) iterator.next();
            if (book.isMatch(name)) {
                matchedBook = book;
                break;
            }
        }
        return matchedBook;
    }
}
